package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.AccountMasterAdapter;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.ContactsModel;
import biznussoft.metercor.model.ItemModel;
import biznussoft.metercor.model.JobCheckListModel;
import biznussoft.metercor.model.ServiceOrderModel;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class AccountsFragment  extends BaseFragment implements OnItemClickListener, OnClickListener{
	private RestClient client;
	public static ArrayList<Bean_Class> list;
	public static ArrayList<ContactsModel> contactsList;
	public static ArrayList<ItemModel> ertDeviceList ;
	public static ArrayList<ItemModel> survayList ;
	public static ArrayList<ItemModel> technician;
	public static HashMap<String, ArrayList<ContactsModel>> subContactsList;
	public static HashMap<String, ArrayList<ServiceOrderModel>> subServiceList;
	public static HashMap<String, ArrayList<JobCheckListModel>> subJobList;
	public static HashMap<String, ArrayList<ItemModel>> subERTDeviceList;
	public static HashMap<String, ArrayList<ItemModel>> subSurveyList;
	public static ArrayList<ServiceOrderModel> serviceList;
	public static ArrayList<JobCheckListModel> jobList;
	private GlobalListener mHomeItemListener;  
	public static ArrayList<ItemModel> modelList;
	public static ArrayList<ItemModel> manufacturerList;
	private ListView lv;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.listfragment, null);                  
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);



		/*MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); */



	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}


		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);      
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);

		Task task = new Task();
		task.execute();        

	}

	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{               
			String accounts = "Select Premise_ID__c,Id,Name,AnnualRevenue,Fax,Phone,NumberOfEmployees,Type,Industry,BillingCity,BillingState,BillingStreet,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingState,ShippingStreet,BillingCountry,BillingPostalCode,Description,Website," +
					"(Select id,LastName,FirstName,AccountId,Title,Phone,MobilePhone,Email,MailingStreet,MailingCity,MailingState,MailingCountry,MailingPostalCode,OtherStreet,OtherCity,OtherState,OtherPostalCode,OtherCountry from Contacts),(select id,name from Surveys__r)," +
					"(SELECT Name,Id,FConnect__Contact_Name__c,FConnect__Account_Name__c,FConnect__Account__c,FConnect__Adress__c,FConnect__Billable__c,FConnect__Bill_To_Address__c,FConnect__Contact__c,FConnect__Site_Name__c,FConnect__No_Of_Activities__c FROM FConnect__Service_Orders__r)," +
					"(select id,Name,Location__c,Conduct_By__c,Date__c,No_of_Employees__c from Jobsite_Inspection_Checklists__r),(select Id,Name from AMR_Device_Installation__r) from Account";


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {           

						Log.i("NCS","RestResponse name :"+result);

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						list = new ArrayList<Bean_Class>();


						subSurveyList = new HashMap<String, ArrayList<ItemModel>>();
						subContactsList = new HashMap<String, ArrayList<ContactsModel>>();
						subServiceList = new HashMap<String, ArrayList<ServiceOrderModel>>();
						subJobList = new HashMap<String, ArrayList<JobCheckListModel>>();
						subERTDeviceList = new HashMap<String, ArrayList<ItemModel>>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							survayList = new ArrayList<ItemModel>();

							contactsList = new ArrayList<ContactsModel>();
							serviceList = new ArrayList<ServiceOrderModel>();
							jobList = new ArrayList<JobCheckListModel>();
							ertDeviceList = new ArrayList<ItemModel>();
							if(!jsonArray.isNull(i)){
								Bean_Class bean = _gson.fromJson(jsonArray.getString(i), Bean_Class.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								list.add(bean);            



								try{
									JSONObject contacts = jsonArray.getJSONObject(i).getJSONObject("Contacts");
									JSONArray contactsArray = contacts.getJSONArray("records");

									Gson contactsList_gson = new Gson();
									for(int j=0; j< contactsArray.length(); j++)
									{
										if(!contactsArray.isNull(j)){
											ContactsModel contactbean = contactsList_gson.fromJson(contactsArray.getString(j), ContactsModel.class);
											contactsList.add(contactbean);


										}
									}

									subContactsList.put(ID, contactsList);


								}catch(Exception e){
									Log.i("NCS","Contacts Exception   is  :"+e.getMessage());
								}


								try{
									JSONObject contacts = jsonArray.getJSONObject(i).getJSONObject("Surveys__r");
									JSONArray contactsArray = contacts.getJSONArray("records");

									Gson contactsList_gson = new Gson();
									for(int j=0; j< contactsArray.length(); j++)
									{
										if(!contactsArray.isNull(j)){
											ItemModel contactbean = contactsList_gson.fromJson(contactsArray.getString(j), ItemModel.class);
											survayList.add(contactbean);


										}
									}

									subSurveyList.put(ID, survayList);


								}catch(Exception e){
									Log.i("NCS","Contacts Exception   is  :"+e.getMessage());
								}

								try{
									JSONObject ertDeviceObject = jsonArray.getJSONObject(i).getJSONObject("AMR_Device_Installation__r");
									JSONArray ertDeviceArray = ertDeviceObject.getJSONArray("records");


									Gson ertGson = new Gson();
									for(int j=0; j< ertDeviceArray.length(); j++)
									{
										if(!ertDeviceArray.isNull(j)){
											ItemModel contactbean = ertGson.fromJson(ertDeviceArray.getString(j), ItemModel.class);
											ertDeviceList.add(contactbean);


										}
									}

									subERTDeviceList.put(ID, ertDeviceList);

								}catch(Exception ex){
									Log.i("NCS","AMRException   is  :"+ex.getMessage());
								}

								try{
									JSONObject serviceOrderObject = jsonArray.getJSONObject(i).getJSONObject("FConnect__Service_Orders__r");
									JSONArray serviceOrderArray = serviceOrderObject.getJSONArray("records");


									Gson serviceOrder_gson = new Gson();
									for(int k=0; k<serviceOrderArray.length(); k++)
									{
										if(!serviceOrderArray.isNull(k)){
											ServiceOrderModel serviceBean =serviceOrder_gson.fromJson(serviceOrderArray.getString(k), ServiceOrderModel.class);
											serviceList.add(serviceBean);


										}
									}

									subServiceList.put(ID, serviceList);

								}catch(Exception ex){
									Log.i("NCS","Service Exception   is  :"+ex.getMessage());
								}
								try{
									JSONObject jobCheckObject = jsonArray.getJSONObject(i).getJSONObject("Jobsite_Inspection_Checklists__r");
									JSONArray jobCheckArray = jobCheckObject
											.getJSONArray("records");

									Gson JobCheckList_gson = new Gson();
									for (int l = 0; l < jobCheckArray.length(); l++) {
										if (!jobCheckArray.isNull(l)) {
											JobCheckListModel jobcheckBean = JobCheckList_gson.fromJson(
													jobCheckArray.getString(l),
													JobCheckListModel.class);
											jobList.add(jobcheckBean);
										}
									}

									subJobList.put(ID, jobList);
								}
								catch (Exception e) {
									Log.i("NCS","Exception   is  :"+e.getMessage());
								}
							}
						}


						showRecords();

					} catch (Exception e) {
						Log.i("NCS","Exception  1 is  :"+e.getMessage());
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

		try{

			String accounts = "select id,name from Manufacturer__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {    

						Log.i("TPT","RestResponse  2 is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						manufacturerList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								manufacturerList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}

		try{

			String accounts = "select id,name from Model__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {            
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						modelList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								modelList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}

		try{


			String accounts = "select name from FConnect__Group_Members__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {            
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						technician = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								technician.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});





		}catch(Exception ex){

		}


	}


	public void showRecords(){
		AccountMasterAdapter adapter = new AccountMasterAdapter(getActivity(),list);
		lv.setAdapter(adapter);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		setHasOptionsMenu(false);
		mHomeItemListener.onCategoryClicked(position);
	}

	public void onClick(View arg0) {
		mHomeItemListener.onCategoryClicked(-1);                     

	}
}

